/*
Copyright [2020] [https://www.xiaonuo.vip]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

  http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

Snowy采用APACHE LICENSE 2.0开源协议，您在使用过程中，需要注意以下几点：

1.请不要删除和修改根目录下的LICENSE文件。
2.请不要删除和修改Snowy源码头部的版权声明。
3.请保留源码和相关描述文件的项目出处，作者声明等。
4.分发源码时候，请注明软件出处 https://gitee.com/xiaonuobase/snowy
5.在修改包名，模块名称，项目代码等时，请注明软件出处 https://gitee.com/xiaonuobase/snowy
6.若您的项目无法满足以上几点，可申请商业授权，获取Snowy商业授权许可，请在官网购买授权，地址为 https://www.xiaonuo.vip
 */
package vip.xiaonuo.modular.manage.biindexdata.service.impl;

import cc.blynk.clickhouse.ClickHouseConnection;
import cc.blynk.clickhouse.ClickHouseDataSource;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import vip.xiaonuo.core.exception.ServiceException;
import vip.xiaonuo.core.factory.PageFactory;
import vip.xiaonuo.core.pojo.page.PageResult;
import vip.xiaonuo.core.util.PoiUtil;
import vip.xiaonuo.dbs.core.annotation.DataSource;
import vip.xiaonuo.modular.common.LoadClickhouseDatasource;
import vip.xiaonuo.modular.common.WdAnalysisConst;
import vip.xiaonuo.modular.enums.IndexLevelEnum;
import vip.xiaonuo.modular.gaode.CoordinateConvertAddr;
import vip.xiaonuo.modular.manage.basemetadata.entity.BaseMetadata;
import vip.xiaonuo.modular.manage.basemetadata.service.BaseMetadataService;
import vip.xiaonuo.modular.manage.biindexdata.entity.BiIndexData;
import vip.xiaonuo.modular.manage.biindexdata.enums.BiIndexDataExceptionEnum;
import vip.xiaonuo.modular.manage.biindexdata.mapper.BiIndexDataMapper;
import vip.xiaonuo.modular.manage.biindexdata.param.BiIndexDataParam;
import vip.xiaonuo.modular.manage.biindexdata.service.BiIndexDataService;
import vip.xiaonuo.modular.manage.biindexdatasum.service.BiIndexDataSumService;
import vip.xiaonuo.modular.manage.biindextype.entity.BaseDataTitleRelevance;
import vip.xiaonuo.modular.manage.biindextype.service.BaseDataTitleRelevanceService;
import vip.xiaonuo.modular.manage.busidatarecord.entity.BusinessDataRecord;
import vip.xiaonuo.modular.manage.busidatarecord.service.BusinessDataRecordService;
import vip.xiaonuo.modular.manage.tsdatarecord.entity.BaseDataDefine;
import vip.xiaonuo.modular.manage.tsdatarecord.entity.BaseDataTable;
import vip.xiaonuo.modular.manage.tsdatarecord.service.BaseDataTableService;
import vip.xiaonuo.sys.modular.area.service.SysAreaService;
import vip.xiaonuo.util.GenerateUniqueIdUtil;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * 指标数据service接口实现类
 *
 * @author cy
 * @date 2022-07-28 19:22:40
 */
@Service
@Slf4j
public class BiIndexDataServiceImpl extends ServiceImpl<BiIndexDataMapper, BiIndexData> implements BiIndexDataService {

    @Resource
    private BusinessDataRecordService businessDataRecordService;

    @Resource
    private BaseDataTableService baseDataTableService;

    @Resource
    private BaseMetadataService baseMetadataService;

    @Resource
    private BaseDataTitleRelevanceService baseDataTitleRelevanceService;

    @Resource
    private BiIndexDataSumService biIndexDataSumService;

    @Resource
    private SysAreaService sysAreaService;


    @Override
    public PageResult<BiIndexData> page(BiIndexDataParam biIndexDataParam) {
        QueryWrapper<BiIndexData> queryWrapper = new QueryWrapper<>();
        if (ObjectUtil.isNotNull(biIndexDataParam)) {

            // 根据省会 查询
            if (ObjectUtil.isNotEmpty(biIndexDataParam.getProvName())) {
                queryWrapper.lambda().eq(BiIndexData::getProvName, biIndexDataParam.getProvName());
            }
            // 根据城市 查询
            if (ObjectUtil.isNotEmpty(biIndexDataParam.getCityName())) {
                queryWrapper.lambda().eq(BiIndexData::getCityName, biIndexDataParam.getCityName());
            }
            // 根据地区 查询
            if (ObjectUtil.isNotEmpty(biIndexDataParam.getCountryName())) {
                queryWrapper.lambda().eq(BiIndexData::getCountryName, biIndexDataParam.getCountryName());
            }
            // 根据经度 查询
            if (ObjectUtil.isNotEmpty(biIndexDataParam.getLng())) {
                queryWrapper.lambda().eq(BiIndexData::getLng, biIndexDataParam.getLng());
            }
            // 根据纬度 查询
            if (ObjectUtil.isNotEmpty(biIndexDataParam.getLat())) {
                queryWrapper.lambda().eq(BiIndexData::getLat, biIndexDataParam.getLat());
            }
            // 根据网格 查询
            if (ObjectUtil.isNotEmpty(biIndexDataParam.getGrid())) {
                queryWrapper.lambda().eq(BiIndexData::getGrid, biIndexDataParam.getGrid());
            }
            // 根据类型 查询
            if (ObjectUtil.isNotEmpty(biIndexDataParam.getTypeId())) {
                queryWrapper.lambda().eq(BiIndexData::getTypeId, biIndexDataParam.getTypeId());
            }
            // 根据指标层级 查询
            if (ObjectUtil.isNotEmpty(biIndexDataParam.getLevel())) {
                queryWrapper.lambda().eq(BiIndexData::getLevel, biIndexDataParam.getLevel());
            }
            // 根据名称 查询
            if (ObjectUtil.isNotEmpty(biIndexDataParam.getName())) {
                queryWrapper.lambda().eq(BiIndexData::getName, biIndexDataParam.getName());
            }
            // 根据值 查询
            if (ObjectUtil.isNotEmpty(biIndexDataParam.getValue())) {
                queryWrapper.lambda().eq(BiIndexData::getValue, biIndexDataParam.getValue());
            }
//            // 根据时间级别 查询
//            if (ObjectUtil.isNotEmpty(biIndexDataParam.getTimeLevel())) {
//                queryWrapper.lambda().eq(BiIndexData::getTimeLevel, biIndexDataParam.getTimeLevel());
//            }
//            // 根据 查询
//            if (ObjectUtil.isNotEmpty(biIndexDataParam.getYear())) {
//                queryWrapper.lambda().eq(BiIndexData::getYear, biIndexDataParam.getYear());
//            }
//            // 根据 查询
//            if (ObjectUtil.isNotEmpty(biIndexDataParam.getMonth())) {
//                queryWrapper.lambda().eq(BiIndexData::getMonth, biIndexDataParam.getMonth());
//            }
//            // 根据 查询
//            if (ObjectUtil.isNotEmpty(biIndexDataParam.getDay())) {
//                queryWrapper.lambda().eq(BiIndexData::getDay, biIndexDataParam.getDay());
//            }
//            // 根据 查询
//            if (ObjectUtil.isNotEmpty(biIndexDataParam.getSeason())) {
//                queryWrapper.lambda().eq(BiIndexData::getSeason, biIndexDataParam.getSeason());
//            }
//            // 根据 查询
//            if (ObjectUtil.isNotEmpty(biIndexDataParam.getWeek())) {
//                queryWrapper.lambda().eq(BiIndexData::getWeek, biIndexDataParam.getWeek());
//            }
            // 根据自定义时间 查询
            if (ObjectUtil.isNotEmpty(biIndexDataParam.getCustomTime())) {
                queryWrapper.lambda().eq(BiIndexData::getCustomTime, biIndexDataParam.getCustomTime());
            }
            // 根据 查询
            if (ObjectUtil.isNotEmpty(biIndexDataParam.getItem1Name())) {
                queryWrapper.lambda().eq(BiIndexData::getItem1Name, biIndexDataParam.getItem1Name());
            }
            // 根据 查询
            if (ObjectUtil.isNotEmpty(biIndexDataParam.getItem1Value())) {
                queryWrapper.lambda().eq(BiIndexData::getItem1Value, biIndexDataParam.getItem1Value());
            }
            // 根据 查询
            if (ObjectUtil.isNotEmpty(biIndexDataParam.getItem2Name())) {
                queryWrapper.lambda().eq(BiIndexData::getItem2Name, biIndexDataParam.getItem2Name());
            }
            // 根据 查询
            if (ObjectUtil.isNotEmpty(biIndexDataParam.getItem2Value())) {
                queryWrapper.lambda().eq(BiIndexData::getItem2Value, biIndexDataParam.getItem2Value());
            }
            // 根据 查询
            if (ObjectUtil.isNotEmpty(biIndexDataParam.getItem3Name())) {
                queryWrapper.lambda().eq(BiIndexData::getItem3Name, biIndexDataParam.getItem3Name());
            }
            // 根据 查询
            if (ObjectUtil.isNotEmpty(biIndexDataParam.getItem3Value())) {
                queryWrapper.lambda().eq(BiIndexData::getItem3Value, biIndexDataParam.getItem3Value());
            }
            // 根据 查询
            if (ObjectUtil.isNotEmpty(biIndexDataParam.getItem4Name())) {
                queryWrapper.lambda().eq(BiIndexData::getItem4Name, biIndexDataParam.getItem4Name());
            }
            // 根据 查询
            if (ObjectUtil.isNotEmpty(biIndexDataParam.getItem4Value())) {
                queryWrapper.lambda().eq(BiIndexData::getItem4Value, biIndexDataParam.getItem4Value());
            }
            // 根据 查询
            if (ObjectUtil.isNotEmpty(biIndexDataParam.getItem5Name())) {
                queryWrapper.lambda().eq(BiIndexData::getItem5Name, biIndexDataParam.getItem5Name());
            }
            // 根据 查询
            if (ObjectUtil.isNotEmpty(biIndexDataParam.getItem5Value())) {
                queryWrapper.lambda().eq(BiIndexData::getItem5Value, biIndexDataParam.getItem5Value());
            }
        }
        return new PageResult<>(this.page(PageFactory.defaultPage(), queryWrapper));
    }

    @Override
    public List<BiIndexData> list(BiIndexDataParam biIndexDataParam) {
        return this.list();
    }

    @Override
    public void add(BiIndexDataParam biIndexDataParam) {
        BiIndexData biIndexData = new BiIndexData();
        BeanUtil.copyProperties(biIndexDataParam, biIndexData);
        this.save(biIndexData);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(List<BiIndexDataParam> biIndexDataParamList) {
        biIndexDataParamList.forEach(biIndexDataParam -> {
            this.removeById(biIndexDataParam.getId());
        });
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void edit(BiIndexDataParam biIndexDataParam) {
        BiIndexData biIndexData = this.queryBiIndexData(biIndexDataParam);
        BeanUtil.copyProperties(biIndexDataParam, biIndexData);
        this.updateById(biIndexData);
    }

    @Override
    public BiIndexData detail(BiIndexDataParam biIndexDataParam) {
        return this.queryBiIndexData(biIndexDataParam);
    }

    /**
     * 获取指标数据
     *
     * @author cy
     * @date 2022-07-28 19:22:40
     */
    private BiIndexData queryBiIndexData(BiIndexDataParam biIndexDataParam) {
        BiIndexData biIndexData = this.getById(biIndexDataParam.getId());
        if (ObjectUtil.isNull(biIndexData)) {
            throw new ServiceException(BiIndexDataExceptionEnum.NOT_EXIST);
        }
        return biIndexData;
    }

    @Override
    @DataSource(name = WdAnalysisConst.CLICKHOUSE_DATASOURCE)
    public void export(BiIndexDataParam biIndexDataParam) {
        QueryWrapper<BiIndexData> queryWrapper = new QueryWrapper<>();

        if (ObjectUtil.isNotNull(biIndexDataParam)) {
            // 根据省会 查询
            if (ObjectUtil.isNotEmpty(biIndexDataParam.getProvName())) {
                queryWrapper.lambda().eq(BiIndexData::getProvName, biIndexDataParam.getProvName());
            }
            // 根据城市 查询
            if (ObjectUtil.isNotEmpty(biIndexDataParam.getCityName())) {
                queryWrapper.lambda().eq(BiIndexData::getCityName, biIndexDataParam.getCityName());
            }
            // 根据地区 查询
            if (ObjectUtil.isNotEmpty(biIndexDataParam.getCountryName())) {
                queryWrapper.lambda().eq(BiIndexData::getCountryName, biIndexDataParam.getCountryName());
            }
            // 根据类型名称
            if (ObjectUtil.isNotEmpty(biIndexDataParam.getTypeId())) {
                queryWrapper.lambda().eq(BiIndexData::getTypeId, biIndexDataParam.getTypeId());
            }
            List<BiIndexData> list = this.list(queryWrapper);
            PoiUtil.exportExcelWithStream("SnowyBiindexDataTags.xls", BiIndexData.class, list);
        }
    }

    @Override
    public List<BiIndexData> indexDataList(BiIndexDataParam biIndexDataParam) {
        LambdaQueryWrapper<BiIndexData> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(BiIndexData::getTypeId,biIndexDataParam.getTypeId());
        if(IndexLevelEnum.GRID.getCode() == biIndexDataParam.getLevel()){
            wrapper.eq(BiIndexData::getProvName,biIndexDataParam.getProvName());
            wrapper.eq(BiIndexData::getCityName,biIndexDataParam.getCityName());
            wrapper.eq(BiIndexData::getCountryName,biIndexDataParam.getCountryName());
        }else if(IndexLevelEnum.POI.getCode() == biIndexDataParam.getLevel()){
            wrapper.eq(BiIndexData::getGrid,biIndexDataParam.getGrid());
        }
        //指标时间级别
//        if(TimeLevelEnum.YEAR.getCode()==biIndexDataParam.getTimeLevel()){
//            wrapper.eq(BiIndexData::getYear,biIndexDataParam.getYear());
//        }
//        if(TimeLevelEnum.MONTH.getCode()==biIndexDataParam.getTimeLevel()){
//            wrapper.eq(BiIndexData::getMonth,biIndexDataParam.getMonth());
//        }
//        if(TimeLevelEnum.DAY.getCode()==biIndexDataParam.getTimeLevel()){
//            wrapper.eq(BiIndexData::getDay,biIndexDataParam.getDay());
//        }
//        if(TimeLevelEnum.SEASON.getCode()==biIndexDataParam.getTimeLevel()){
//            wrapper.eq(BiIndexData::getSeason,biIndexDataParam.getSeason());
//        }
//        if(TimeLevelEnum.WEEK.getCode()==biIndexDataParam.getTimeLevel()){
//            wrapper.eq(BiIndexData::getWeek,biIndexDataParam.getWeek());
//        }
        return this.getBaseMapper().selectList(wrapper);
    }

    @Override
    public void addData(BaseDataDefine record) {
        BusinessDataRecord businessDataRecord = businessDataRecordService.findById(record.getRecordId());
//        文件对应的tables列表
            List<BaseDataTable> baseDataTables = baseDataTableService.findListByRecordId(businessDataRecord.getId());
            businessDataRecord.setBaseDataTables(baseDataTables);
//        文件解析出的数据列表
            List<BaseMetadata> baseMetadataList = baseMetadataService.findByRecordId(businessDataRecord.getId().toString());
            businessDataRecord.setBaseMetadatas(baseMetadataList);

//        根据tablesids查询出对应表中的指标分类信息
            List<Long> ids = new ArrayList<>();
            for (BaseDataTable baseDataTable : baseDataTables) {
                ids.add(baseDataTable.getId());
            }
            List<BaseDataTitleRelevance> baseDataTitleRelevances = baseDataTitleRelevanceService.findByIds(ids);
//          文件解析出的数据列表
            List<BaseMetadata> baseMetadatas = businessDataRecord.getBaseMetadatas();

            for (BaseMetadata baseMetadata : baseMetadatas) {
//            获取json字符串，获取经纬度

                JSONObject jsonObject = JSON.parseObject(baseMetadata.getContent());
                String index1 = jsonObject.getString("index1");
                String[] split = index1.split("\\(\\(\\(");

                String[] splitloc = index1.replace("(", "").replace(")", "").split(",");
                String location = splitloc[splitloc.length - 1].trim().replace(" ", ",");
//            根据经纬度获取到省市县
                String[] locationAddr = CoordinateConvertAddr.getBatchLocationAddr(location);

                baseMetadata.setBigGridId(GenerateUniqueIdUtil.getGuid());
                baseMetadata.setLng(new BigDecimal(locationAddr[0]));
                baseMetadata.setLat(new BigDecimal(locationAddr[1]));
                baseMetadata.setProvName(locationAddr[2]);
                baseMetadata.setCityName(locationAddr[3]);
                baseMetadata.setCountryName(locationAddr[4]);
//              经纬度
                baseMetadata.setLnglat(index1);
            }

//          测试method
//            for (BaseDataTable baseDataTable : baseDataTables) {
//                for (BaseDataTitleRelevance baseDataTitleRelevance : baseDataTitleRelevances) {
//                    if (baseDataTable.getId().compareTo(baseDataTitleRelevance.getTableId())==0){
//                        baseDataTable.setTitle(baseDataTitleRelevance.getRelevanceName());
//                        baseDataTable.setTypeId(baseDataTitleRelevance.getIndexTypeId());
//                    }
//                }
//            }


//      初始化数据
        for (BaseDataTitleRelevance baseDataTitleRelevance : baseDataTitleRelevances) {
            for (BaseDataTable baseDataTable : baseDataTables) {
                if (baseDataTitleRelevance.getTableId().compareTo(baseDataTable.getId())==0){
                    baseDataTitleRelevance.setDataIndex(baseDataTable.getDataIndex());
                }
            }
        }

//      时间信息初始化
        String year = "";
        String month = "";
        String day = "";
        if (record.getTimeLevel().equals("year")){
             year = record.getTime();
        }
        if (record.getTimeLevel().equals("month")){
            String ts = record.getTime().split("T")[0];
             year = ts.split("-")[0];
             month = ts.split("-")[0] + "-" + ts.split("-")[1];
        }
        if (record.getTimeLevel().equals("day")){
            String ts = record.getTime().split("T")[0];
            year = ts.split("-")[0];
            month = ts.split("-")[0] + "-" + ts.split("-")[1];
             day = ts.split("-")[0] + "-" + ts.split("-")[1] +"-"+ts.split("-")[2];
        }


//      添加指标数据
            List<BiIndexData> biIndexDataList = new ArrayList<>();
            for (BaseMetadata baseMetadata : baseMetadatas) {
                for (BaseDataTitleRelevance baseDataTitleRelevance : baseDataTitleRelevances) {
                    JSONObject jsonObject = JSON.parseObject(baseMetadata.getContent());
                    BiIndexData biIndexData = new BiIndexData();
                    biIndexData.setLng(baseMetadata.getLng().toString());
                    biIndexData.setLat(baseMetadata.getLat().toString());
                    biIndexData.setLnglat(baseMetadata.getLnglat());
                    biIndexData.setProvName(baseMetadata.getProvName());
                    biIndexData.setCityName(baseMetadata.getCityName());
                    biIndexData.setCountryName(baseMetadata.getCountryName());
                    biIndexData.setGrid(baseMetadata.getBigGridId());
//  测试demo
                    biIndexData.setTypeId(baseDataTitleRelevance.getIndexTypeId());
                    biIndexData.setName(baseDataTitleRelevance.getRelevanceName());
                    biIndexData.setValue(jsonObject.getString(baseDataTitleRelevance.getDataIndex()));
//  测试demo
                    biIndexData.setMultipolygon(baseMetadata.getLnglat());
                    biIndexData.setRecordId(record.getRecordId().toString());
                    biIndexData.setId(Long.valueOf(GenerateUniqueIdUtil.getGuid()));

                    biIndexData. setYear(year);
                    biIndexData. setMonth(month);
                    biIndexData. setDay(day);

                    biIndexDataList.add(biIndexData);

                }
            }
        ClickHouseConnection connection = null;
        try {
            ClickHouseDataSource clickHouseDataSource = LoadClickhouseDatasource.get();
            connection = clickHouseDataSource.getConnection();
            connection.setAutoCommit(false);
            ClickHouseConnection finalConnection = connection;
            this.addClickHouse(biIndexDataList, finalConnection);
            log.info("解析完成！！！");
        } catch (Exception e) {
            log.error(biIndexDataList.get(0) + " >>> 添加失败", e);
        } finally {
            if (connection != null) {
                try {
                    connection.close();
                } catch (SQLException ignore) {
                }
            }
        }
    }

    final String insertSql = "insert into bi_index_data" +
            "(prov_name,city_name,country_name,lng,lat,grid,type_id,`name`,`value`, multipolygon , record_id , id , `year` ,`month` , `day`) " +
            "values (?, ?, ? , ? , ? , ?, ? , ? , ? , ? , ? , ? , ? , ? , ?)";

    public void addClickHouse(List<BiIndexData> list , ClickHouseConnection connection) {
        // 注意这里使用的CK自己实现的PreparedStatement
        PreparedStatement preparedStatement = null;
        try {
            preparedStatement = connection.prepareStatement(insertSql);
            for (BiIndexData biIndexData : list) {
                preparedStatement.setString(1, biIndexData.getProvName());
                preparedStatement.setString(2, biIndexData.getCityName());
                preparedStatement.setString(3, biIndexData.getCountryName());
                preparedStatement.setString(4, biIndexData.getLng());
                preparedStatement.setString(5, biIndexData.getLat());
                preparedStatement.setString(6, biIndexData.getGrid());
                preparedStatement.setLong(7, biIndexData.getTypeId());
                preparedStatement.setString(8, biIndexData.getName());
                preparedStatement.setString(9, biIndexData.getValue());
                preparedStatement.setString(10, biIndexData.getMultipolygon());
                preparedStatement.setString(11, biIndexData.getRecordId());
                preparedStatement.setLong(12, biIndexData.getId());
                preparedStatement.setString(13, biIndexData.getYear());
                preparedStatement.setString(14, biIndexData.getMonth());
                preparedStatement.setString(15, biIndexData.getDay());
                preparedStatement.addBatch();
            }
            preparedStatement.executeBatch();
            connection.commit();
        } catch (SQLException e) {
            log.error(list.get(0).getTypeId() + ">>>写入数据库失败", e);
        } finally {
            if (preparedStatement != null) {
                try {
                    preparedStatement.close();
                } catch (SQLException ignore) {
                }
            }
        }
    }

    @Override
    @DataSource(name = WdAnalysisConst.CLICKHOUSE_DATASOURCE)
    public PageResult<BiIndexData> indexDataListCHPage( BiIndexDataParam biIndexDataParam) {

//        时间条件
        if (StringUtils.isNotBlank(biIndexDataParam.getMonth())){
            biIndexDataParam.setYear(biIndexDataParam.getMonth().split("-")[0].replace("\"",""));
            biIndexDataParam.setMonth(biIndexDataParam.getMonth().split("-")[0] +"-"+biIndexDataParam.getMonth().split("-")[1]);
        }
        if (StringUtils.isNotBlank(biIndexDataParam.getDay())){
            biIndexDataParam.setDay(biIndexDataParam.getDay().split("T")[0].replace("\"",""));
            biIndexDataParam.setMonth(biIndexDataParam.getDay().split("T")[0].split("-")[0] +"-"+biIndexDataParam.getMonth().split("T")[0].split("-")[1]);
        }
        System.out.println(biIndexDataParam.getYear());
        System.out.println(biIndexDataParam.getMonth());
        return  new PageResult<>(this.baseMapper.pageIndexData(PageFactory.defaultPage(), biIndexDataParam));
    }

    @Override
    @DataSource(name = WdAnalysisConst.CLICKHOUSE_DATASOURCE)
    public List<BiIndexData> findByRecordId(String id) {
        QueryWrapper<BiIndexData> queryWrapper=new QueryWrapper<>();
        queryWrapper.lambda().eq(BiIndexData::getRecordId,id);
        List<BiIndexData> list = this.list(queryWrapper);
        return list;
    }

    @Override
    @DataSource(name = WdAnalysisConst.CLICKHOUSE_DATASOURCE)
    public List<BiIndexData> findByTypeId(BiIndexDataParam biIndexDataParam) {
        List<BiIndexData> list = this.baseMapper.IndexDataList(biIndexDataParam);
        return list;
    }

    @Override
    @DataSource(name = WdAnalysisConst.CLICKHOUSE_DATASOURCE)
    public List<BiIndexData> findByTypeIds(List<Long> typeIds) {
        List<BiIndexData> byTypeIds = this.baseMapper.findByTypeIds(typeIds);
        return byTypeIds;
    }

    public JSONArray changeMultipolygon(String s){
        JSONArray array = new JSONArray();
        if(s.startsWith("MULTIPOLYGON (((") && s.endsWith(")))")){
            String substring = s.substring(16, s.length() - 3);
            substring = substring.replaceAll("\\(","").replaceAll("\\)","");
            String[] split = substring.split(",");
            for (String p : split) {
                String[] latlng = p.trim().split(" ");
                JSONArray element = new JSONArray();
                element.add(Double.parseDouble(latlng[0]));
                element.add(Double.parseDouble(latlng[1]));
                array.add(element);
            }
        }else if(s.startsWith("[")){
            array = JSONArray.parseArray(s);
        }else{
            try {
                String[] split = s.split(",");
                for (String p : split) {
                    String[] latlng = p.trim().split(" ");
                    JSONArray element = new JSONArray();
                    element.add(Double.parseDouble(latlng[0]));
                    element.add(Double.parseDouble(latlng[1]));
                    array.add(element);
                }
            } catch (Exception e) {
            }
        }
        return array;
    }
}
